;(function(win){
	function SelectHeadImg(){
		
	}
	
	SelectHeadImg.prototype = {
		constructor: SelectHeadImg,
		init: function(opt){
			var $this = this
				
			$this.el = opt.el
			$this.fileDom = opt.fileDom
			$this.headImgDom = opt.headImgDom
			
			$this.crateMask($this.el)
			$this.imgDom = $this.el.children("img")
			
			$this.move($this.el)
			$this.bindEvent($this.el)
			$this.fileChange(opt.fileDom)
		},
		crateMask: function(el){
			var $this = this
			el.children(".cut_window").css({
				"height": $this.window_width,
				"margin-top": -$this.window_width / 2
			})
			//创建遮罩
			if(el.children(".mask").length === 0){
				var _height = ($this.window_height - $this.window_width) / 2
					mask = "<div class='mask' style='top: 0;height: "+ _height +"px;'></div>"+
						   "<div class='mask' style='bottom: 0;height: "+ _height +"px;line-height: "+ _height +"px;'>"+
						   "	<a class='btn cancel'>取消</a>"+
						   "	<a class='btn ok'>选取</a>"+
						   "</div>";
				el.append(mask)
			}
		},
		el: null,
		fileDom: null,
		headImgDom: null,
		show: true,
		cutWidth: 400,//剪裁后的图片宽度
		cutHeight: 400,
		window_width: $(window).width(),
		window_height: $(window).height(),
		imgDom: null,
		translateX: 0,//tarnslate移动位置
		translateY: 0,
		overflowY: 0,//图片超出剪裁框部分的一半
		fileChange: function(fileDom){
			var $this = this
			fileDom[0].addEventListener("touchstart",function(){
				if(!$this.show){
					$(this).attr("disabled",true)
				}else{
					$(this).removeAttr("disabled")
				}
			})
			fileDom.change(function(){
				var that = $(this),
					file = that[0].files[0]
				if(file){ 
	                var dianIndex = file.name.indexOf("."),
	                	name = "";
	                //验证格式
	                if(dianIndex != -1){
	                	name = file.name.substring(dianIndex);
	                	if(!_x.isImage(name)){
	                        _x.showTip("请上传图片，格式为jpg/jpeg/png/gif");
	                        that.val("");
	                        return false;
	                    }
	                }
	            
	                //验证大小
	                if(file.size > 4194304){
	                    _x.showTip("图片大小超出限制");
	                    that.val("");
	                    return false;
	                }
	                _x.window_loading()
	                $this.show = false
					$this.readerImg(file)
				}
				
			}) 
		},
		//读取图片信息
		readerImg: function(file){
			var $this = this,
				reader = new FileReader()
			reader.readAsDataURL(file)
			reader.onload = function(){
				var image = new Image()
				image.src = this.result
				if(image.complete){
					$this.orientation(image)
				}else{
					image.onload = function(){
						$this.orientation(this)
					}
				}
			}
		},
		orientation: function(image){
			var $this = this
			EXIF.getData(image, function(){
	            var orientation = EXIF.getTag(this, 'Orientation');
	            if(orientation && orientation != 1){//判断是否需要旋转
	            	$this.drawImage(this,orientation)
	            }else{
	            	$this.getImag(this)
	            }
	        });
		},
		getImag: function(image){
			var $this = this,
				el = $this.el,
				$image = new Image()
			
			$image.src = image.src
			if($image.complete){
				var bit = $this.window_width / $image.width
				$this.imgDom.attr("src",$image.src)
				var imgH = bit * $image.height
				$this.imgDom.css({
					"margin-top": -imgH / 2
				})
				_x.window_loading(true)
				$this.el.fadeIn(300)
			}else{
				$image.onload = function(){
					var bit = $this.window_width / this.width
					$this.imgDom.attr("src",this.src)
					var imgH = bit * this.height
					$this.imgDom.css({
						"margin-top": -imgH / 2
					})
					_x.window_loading(true)
					$this.el.fadeIn(300)
				}
			}
		},
		bindEvent: function(el){
			var $this = this
			el.on("click","a.btn",function(){
				if($(this).hasClass("ok")){//选取--上传图片
					$("#testshow").show()
					_x.window_loading()
					$this.cut(el,function(canvas){
						//上传
						$this.upload(canvas)
					})
				}else{
					$this.show = true
				}
				el.fadeOut(300,function(){
					$this.translateX = 0
					$this.translateY = 0
					$this.overflowY = 0
					el.removeClass("trans")
					$this.imgDom.removeAttr("style")
				})
			})
		},
		upload: function(canvas){
			var $this = this
				data = canvas.toDataURL();

			data = data.split(',')[1];
			data = window.atob(data);
			var ia = new Uint8Array(data.length);
			for (var i = 0; i < data.length; i++) {
			    ia[i] = data.charCodeAt(i);
			};

			var blob = new Blob([ia], {type:"image/png"});
			
			var fd = new FormData();
			fd.append($this.fileDom.attr("name"),blob);
			
			var xhr = new XMLHttpRequest()
			xhr.open("post","/userCenter/submitFile",true);
			xhr.addEventListener("load",function(){
                var result = JSON.parse(this.response);
                console.log(result)
                $this.show = true
                _x.showTip("上传成功！");
                $this.headImgDom.attr("src",canvas.toDataURL())
                _x.window_loading(true)
            });
            
            xhr.addEventListener('error',function(e){//监听XMLHttpRequest对象的progress事件，读取完毕后触发
            	_x.showTip("上传失败,请检查您的网络！");
            	 $this.show = true
            	 _x.window_loading(true)
            });
            
            xhr.send(fd);
			
		},
		move: function(el){
			var $this = this,
				imgDom = $this.imgDom,
				visibleTop = $(el).children(".mask").height(),//可视区域范围
				startX = 0,
				startY = 0,
				moveX = 0,
				moveY = 0,
				$window_height = $this.window_height
				
			el[0].onmousedown = function(){
				if(imgDom.height() > imgDom.width()){
					$this.overflowY = (imgDom.height() - imgDom.width()) / 2
					console.log($this.overflowY)
				}
			}
			
			el[0].addEventListener("touchstart", function(e){
				var touches = e.touches[0]
				startX = touches.pageX
				startY = touches.pageY
				
				if(imgDom.height() > imgDom.width()){
					$this.overflowY = (imgDom.height() - imgDom.width()) / 2
				}
			})
				
			el[0].addEventListener("touchmove", function(e){
				el.removeClass("trans")
				e.preventDefault()
				
				if(e.touches.length > 1){
					return
				}
				
				var touches = e.touches[0]
				moveX = touches.pageX
				moveY = touches.pageY
				var targetX = moveX - startX + $this.translateX,
					targetY = moveY - startY + $this.translateY
				imgDom[0].style.transform = "translate3d("+ targetX +"px,"+ targetY +"px,0)"
				
				$this.translateX = targetX
				$this.translateY = targetY
				
				startX = moveX
				startY = moveY
			})
			
			el[0].addEventListener("touchend", function(){
				el.addClass("trans")
				if($this.translateX < 0 || $this.translateX > 0){
					$this.translateX = 0
				}
				
				if(imgDom.height() > imgDom.width()){//超出剪裁框
					if($this.translateY > $this.overflowY){
						$this.translateY = $this.overflowY
					}else if($this.translateY < 0 && Math.abs($this.translateY) > $this.overflowY){
						$this.translateY = -$this.overflowY
					}
					
				}else{
					if($this.translateY < 0 || $this.translateY > 0){
						$this.translateY = 0
					}
				}
				
				imgDom[0].style.transform = "translate3d("+ $this.translateX +"px,"+ $this.translateY +"px,0)"
			})
		},
		cut: function(el,callback){
			var $this = this,
				_width = el.children(".cut_window").outerWidth(),
				_top = el.children(".cut_window").offset().top,
				_noTop = _top - $this.overflowY,
				imgDom = $this.imgDom,
				imgW = imgDom.width(),
				imgH = imgDom.height(),
				src = el.children("img").attr("src"),
				canvas = document.createElement("canvas"),
				ctx = canvas.getContext("2d"),
				image = new Image(),
				//cutY = (_top - $this.translateY + $this.overflowY),//开始剪切的 y坐标位置。
				//cutY = _top - $this.translateY - _noTop,
				$window_width = $this.window_width,//测试代码
				$window_height = $this.window_height,//测试代码
				cutPosX = 0,
				cutPosY = 0//在画布上放置图像的y 坐标位置
			canvas.width = $this.cutWidth
			canvas.height = $this.cutHeight	
			//console.log($this.overflowY+"-----")
			
			image.src = src
			image.onload = function(){
				var imgBit = this.width / imgW,//图片比例
					cupWidth = this.width,//剪裁图片的宽度
					cupHeight = this.width,//剪裁图片的高度和宽度一致
					_cupWidth = this.width,//剪裁后的宽度
					_cupHeight = $this.cutHeight,
					defCutY = (this.height - this.width) / 2,//默认剪裁Y轴
					maxCutY = this.height - this.width,//最大剪裁Y轴
					cutY = defCutY - $this.translateY * imgBit//实际剪裁位置
			
				if(this.width > this.height){
					var _cupBit = $this.cutWidth / this.width
					_cupHeight = _cupBit * this.height//计算等比例高度
					cutPosY = ($this.cutHeight - _cupHeight) / 2//垂直居中
					
					cupHeight = this.height//使用原图高度
				}
				
				
				if(this.width >= this.height){
					cutY = 0//没有放大情况下正方形图片剪裁Y轴为0
				}else{
					if(cutY > maxCutY){
						cutY = maxCutY//最大剪裁Y轴
					}
				}
				
				if(cutY < 0){
					cutY = 0//最小剪裁Y轴
				}
				
				ctx.drawImage(this, 0, cutY,this.width, cupHeight,0,cutPosY,$this.cutWidth,_cupHeight);
				/*
					画布的宽高就是图片的宽高
					1.img对象
					2.开始剪裁X轴
					3.开始剪裁Y轴
					4.要剪裁的宽度
					5.要剪裁的高度
					6.剪裁后图像放置的X轴
					7.剪裁后图像放置的Y轴
					8.剪裁后的宽度
					9.剪裁后的高度
				*/
				callback(canvas)
				/*$("#testshow").children("img").attr("src",canvas.toDataURL())
				//return canvas.toDataURL()
				var imgData = _x.imgFormat(400,400,$window_width,$window_height)
				$("#testshow").children("img").css({
					"width": imgData.imgWidth,
					"height": imgData.imgHeight,
					"margin-top": -(imgData.imgWidth / 2),
					"margin-left": -(imgData.imgHeight / 2)
				})*/
			}	
		},
		//重绘图片预览
		drawImage: function(image,orientation){
			var $this = this,
				canvas = document.createElement("canvas"), 
	        	ctx = canvas.getContext("2d");  
	        canvas.width = image.width;  
	        canvas.height = image.height;  
	        ctx.drawImage(image, 0, 0);
	        switch(orientation){  
	            case 6://需要顺时针（向左）90度旋转  
	            	$this.rotateImg(image,'left',canvas);  
	                break;  
	            case 8://需要逆时针（向右）90度旋转  
	            	$this.rotateImg(image,'right',canvas);  
	                break;  
	            case 3://需要180度旋转  
	            	$this.rotateImg(image,'right',canvas);//转两次  
	            	$this.rotateImg(image,'right',canvas);  
	                break;  
	        }
			
	        var image = new Image()
	        image.src = canvas.toDataURL()
	        
			if(image.complete){
				var bit = $this.window_width / image.width,
					imgH = bit * image.height
				$this.imgDom.css("margin-top",-imgH / 2).attr("src",image.src)
				_x.window_loading(true)
				$this.el.fadeIn(300)
			}else{
				image.onload = function(){
					var bit = $this.window_width / this.width,
						imgH = bit * this.height
				
					$this.imgDom.css("margin-top",-imgH / 2).attr("src",this.src)
					_x.window_loading(true)
					$this.el.fadeIn(300)
				}
			}
	        
		},
		rotateImg: function(image, direction,canvas){
			//最小与最大旋转方向，图片旋转4次后回到原方向    
	        var min_step = 0;    
	        var max_step = 3;    
	        //var img = document.getElementById(pid);    
	        if (image == null)return;    
	        //img的高度和宽度不能在img元素隐藏后获取，否则会出错    
	        var height = image.height;    
	        var width = image.width;    
	        //var step = img.getAttribute('step');    
	        var step = 2;    
	        if (step == null) {    
	            step = min_step;    
	        }    
	        if (direction == 'right') {    
	            step++;    
	            //旋转到原位置，即超过最大值    
	            step > max_step && (step = min_step);    
	        } else {    
	            step--;    
	            step < min_step && (step = max_step);    
	        }    
	        
	        //旋转角度以弧度值为参数    
	        var degree = step * 90 * Math.PI / 180;    
	        var ctx = canvas.getContext('2d');    
	        switch (step) {    
	            case 0:    
	                canvas.width = width;    
	                canvas.height = height;    
	                ctx.drawImage(image, 0, 0);    
	                break;    
	            case 1:    
	                canvas.width = height;    
	                canvas.height = width;    
	                ctx.rotate(degree);    
	                ctx.drawImage(image, 0, -height);    
	                break;    
	            case 2:    
	                canvas.width = width;    
	                canvas.height = height;    
	                ctx.rotate(degree);    
	                ctx.drawImage(image, -width, -height);    
	                break;    
	            case 3:    
	                canvas.width = height;    
	                canvas.height = width;    
	                ctx.rotate(degree);    
	                ctx.drawImage(image, -width, 0);    
	                break;    
	        }
		}
	}
		
	win.selectHeadImg = SelectHeadImg
})(window)